﻿#region Copyright © 2013 Jared Hawke(Nocturnal)  & John Puttock(DreadNought) - Project Oblivion

/// <copyright>
/// Copyright © 2013 Jared Hawke & John Puttock - Project Oblivion
/// 
/// Start Date: 2/10/2013
/// Project: Minecraft Server Emulator
/// License: Closed Source
/// 
/// Authors: Jared Hawke & John Puttock
/// </copyright>

#endregion

using System;
using System.Net;
using System.Security.Cryptography;
using Oblivion.Networking;
using Oblivion.Substructure;

namespace Oblivion
{
    /// <summary> The entry point for the program. </summary>
    internal class Program
    {
        // Global-Scope Variables:
        public static Configuration Configuration { get; set; }
        public static ServerSocket GameServer { get; set; }

        public static RSAParameters ServerKey { get; set; }
        public static RSACryptoServiceProvider CryptoServiceProvider { get; set; }

        /// <summary>
        /// Writes centered text to the console
        /// </summary>
        public static void WriteLine(string text, ConsoleColor consoleColor = ConsoleColor.Gray)
        {
            ConsoleColor prevColor = Console.ForegroundColor;

            if (consoleColor != ConsoleColor.Gray)
                Console.ForegroundColor = consoleColor;

            Console.WriteLine("{0," + ((Console.WindowWidth/2) + text.Length/2) + "}", text);
            Console.ForegroundColor = prevColor;
        }

        /// <summary> The method to begin the program. </summary>
        private static void Main()
        {
            Console.Title = "Project Oblivion - Minecraft Server Emulator";

            WriteLine("Initializing...", ConsoleColor.Green);

            Configuration = new Configuration(Kernel.ConfigPath);

            // Creates the GameServer, binds it to the port in the configuration and begins listening.
            GameServer = new ServerSocket();
            GameServer.Bind(IPAddress.Any.ToString(), Configuration.PORT);
            GameServer.OnClientConnect += GameWorker.Connect;
            GameServer.OnClientReceive += GameWorker.Receive;
            GameServer.OnClientDisconnect += GameWorker.Disconnect;
            GameServer.Listen(100);

            WriteLine("Generating server key...", ConsoleColor.Magenta);
            GenerateServerKey();
            WriteLine("");
            WriteLine("Server loaded, ready for action!", ConsoleColor.Green);

            // Don't let the program end.
            while (true)
                Console.ReadLine();
        }

        private static void GenerateServerKey()
        {
            CryptoServiceProvider = new RSACryptoServiceProvider(1024);
            ServerKey = CryptoServiceProvider.ExportParameters(true);

            WriteLine("Server key generated.", ConsoleColor.Magenta);
        }
    }
}